package com.liehu.user.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.liehu.user.dao.EmployeeMapper;

import com.liehu.user.pojo.Employee;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import util.EncryptedDataUtils;
import util.IdWorker;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Transactional //事务
public class EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private IdWorker idWorker;//推特雪花id生成器
    @Autowired
    private RedisTemplate redisTemplate;    //Redis缓存
    @Autowired
    private RabbitTemplate rabbitTemplate;  //RabbitMQ消息队列
    @Autowired
    private BCryptPasswordEncoder encoder; //随机加盐机密
    @Autowired
    private HttpServletRequest request;

    /**
     * 根据角色查询业务员
     */
    public List<Employee> findByRoleId(String roleId){
        return employeeMapper.findByRoleId(roleId);
    }

    /**
     * 查询当前登录的用户信息
     */
    public Employee getUserInfo(){
        Claims claims_employee = (Claims) request.getAttribute("claims_employee");
        if(claims_employee == null ){
            return  null;
        }
        String employeeId = claims_employee.getId();
        Employee employee = employeeMapper.selectById(employeeId);
        if(employee == null){
            return  null;
        }
        return  employee;
    }

    /**
     * 查询所有
     */
    public List<Employee> findAll(){
        return employeeMapper.selectList(null);
    }
    /**
     * 根据id查询
     */
    public Employee findById(String id){
        Employee employee = employeeMapper.selectById(id);
        employee.setPassword(null);
        return employee;
    }
    /**
     * 根据电话号码查询
     */
    public Employee findByMobile(String mobile){
        return employeeMapper.findByMobile(mobile);
    }

    /**
     * 插入
     */
    public void save(Employee employee){
        Claims claims2 = (Claims) request.getAttribute("claims_admin");
        if(claims2 == null){
            throw new RuntimeException("权限不足！");
        }
        //给这条记录插入id
        employee.setId(idWorker.nextId()+"");
        //设置默认密码为123456,进行加盐机密处理。
        employee.setPassword(encoder.encode("123456"));
        //插入
        employeeMapper.insert(employee);
    }

    /**
     * 更新
     */
    public void update(Employee employee){
        Claims claims2 = (Claims) request.getAttribute("claims_admin");
        if(claims2 == null){
            throw new RuntimeException("权限不足！");
        }
        //如果是修改密码，则进行加盐机密处理。
        if(employee.getPassword()!=null && !"".equals(employee.getPassword())){
            //密码不为空，则进行加盐机密处理。
            employee.setPassword(encoder.encode(employee.getPassword()));
        }
        employeeMapper.updateById(employee);
    }
    /**
     * 根据id删除
     */
    public void deleteById(String id){
        Claims claims2 = (Claims) request.getAttribute("claims_admin");
        if(claims2 == null){
            throw new RuntimeException("权限不足！");
        }
        employeeMapper.deleteById(id);
    }
    /**
     * 分页查询
     */
    public Page<Employee> findByPage(Integer page,Integer size){
        Page<Employee> pageable = new Page<>(page,size);//创建分页对象
        return  employeeMapper.selectPage(pageable, null);
    }
    /**
     * 条件分页查询
     */
    public Page<Employee> findByPage(Employee employee,Integer page,Integer size){
        Page<Employee> pageable = new Page<>(page,size);//创建分页对象
        QueryWrapper<Employee> wrapper = myWrapper(employee);//创建条件对象wrapper
        return  employeeMapper.selectPage(pageable, wrapper);
    }

    /**
     * 内部处理条件
     * @param employee
     * @return
     */
    private QueryWrapper<Employee> myWrapper(Employee employee){
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();

        //条件构造2
        if(employee.getLoginName()!=null&&!employee.getLoginName().equals("")){
            wrapper.eq("login_name",employee.getLoginName());
        }
        //条件构造3
        if(employee.getId()!=null&&!employee.getId().equals("")){
            wrapper.eq("id",employee.getId());
        }
        //条件构造4
        if(employee.getMobile()!=null&&!employee.getMobile().equals("")){
            wrapper.eq("mobile",employee.getMobile());
        }
        //条件构造5
        if(employee.getStatus()!=null&&!employee.getStatus().equals("")){
            wrapper.eq("status",employee.getStatus());
        }
        return  wrapper;
    }

    /**
     * 发送短信
     * @param mobile
     */
    public void sendMsm(String mobile) {
        //1.生成6位数的随机短信
        String checkCode = RandomStringUtils.randomNumeric(6);
        //2.在redis中存取该验证码，有效时间为30分钟
        redisTemplate.opsForValue().set("checkCode"+mobile,checkCode,30L, TimeUnit.MINUTES);
        System.out.println(checkCode);
        //3.将手机号码和验证码推送给消息队列。
        Map<String,String> map = new HashMap<>(); //使用map封装参数。
        map.put("mobile",mobile);
        map.put("checkCode",checkCode);
        System.out.println(map);
        rabbitTemplate.convertAndSend("sms",map);
    }

    /**
     * 根据工号+密码登录
     * @param jobNumber
     * @param password
     * @return
     */
    public Employee loginByPassword(String jobNumber, String password) {
        //根据工号查询
        Employee employee = employeeMapper.findByJobNumber(jobNumber);
        //如果查询的结果 不为空并且密码正确，则返回查询到的结果。
        if(employee!=null && encoder.matches(password,employee.getPassword())){
            employee.setPassword(null);//将密码清空后再返回。
            return employee;
        }
        //否则直接返回Null;
        return null;
    }

    /**
     * 修改当前登录用户的密码
     * @param password
     */
    public void updateByPassword(String password) {
        //先获取token
        Claims claims = (Claims) request.getAttribute("claims_employee");
        if(claims == null){
            throw new RuntimeException("权限不足！");
        }
        //获取token内的信息
        String id = claims.getId();
        //更新数据，对密码进行加盐机密处理
        employeeMapper.updateByPassword(id,encoder.encode(password));

    }
    /**
     * 修改员工的状态为离职，且需要管理员权限操作
     */
    public void updateStatus(String employeeId) {
        //先获取token
        Claims claims = (Claims) request.getAttribute("claims_admin");
        if(claims == null){
            throw new RuntimeException("权限不足！");
        }
        String adminId = claims.getId();
        employeeMapper.updateStatus(employeeId);
        //将修改后的信息交给消息队列，处理业务员队列的信息
        Map<String,String> map = new HashMap<>();
        map.put("state","2");
        map.put("employeeId",employeeId);
        rabbitTemplate.convertAndSend("employeeList",map);
    }
    /**
     * 刷新(更新)业务员队列
     */
    public void updateEmployeeList(String roleId) {
        //将修改后的信息交给消息队列，处理业务员队列的信息
        Map<String,String> map = new HashMap<>();
        map.put("state","0");
        map.put("roleId",roleId);
        rabbitTemplate.convertAndSend("employeeList",map);

    }
}
